extends CharacterBody2D

enum anim_state { IDLE, RUN, ATTACK }
@onready var p_anim_state = anim_state.IDLE
@onready var navi = $NavigationAgent2D
@onready var SPEED: float = 150.0
var cam: Camera2D
var sprite :AnimatedSprite2D




func _enter_tree():
	set_multiplayer_authority(name.to_int())

func _ready():
	cam = $"../../Camera2D"
	sprite = $p1
	cam.anchor_mode = Camera2D.ANCHOR_MODE_DRAG_CENTER
	if is_multiplayer_authority():
		sprite.animation_finished.connect(on_animation_finished)
	update_animation()  # 初始化动画

func on_animation_finished():
	if p_anim_state == anim_state.ATTACK:
		stop_moving()


func _physics_process(delta):
	if not is_multiplayer_authority():
		return  # 只有控制该角色的客户端执行移动逻辑
	
	cam.global_position = global_position
	
	# 移动逻辑
	if p_anim_state == anim_state.RUN:
		if navi.distance_to_target() > 5:
			var next_position = navi.get_next_path_position()
			velocity = global_position.direction_to(next_position) * SPEED
		else:
			stop_moving()
	else:
		velocity = Vector2.ZERO

	move_and_slide()
	update_animation()  # 本地更新动画

func _unhandled_input(event: InputEvent):
	if not is_multiplayer_authority():
		return
	
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
		p_anim_state = anim_state.RUN
		var target = get_global_mouse_position() #设置目标位置
		navi.set_target_position(target)
		var final_position = navi.get_final_position() #设置最终目标位置，避免抖动
		navi.set_target_position(final_position)
		sync_anim_state.rpc(p_anim_state)  # 同步动画状态给其他客户端
	if event is InputEventKey and event.keycode == KEY_Q and event.pressed:
		p_anim_state = anim_state.ATTACK
		sync_anim_state.rpc(p_anim_state)



func stop_moving():
	p_anim_state = anim_state.IDLE
	sync_anim_state.rpc(p_anim_state)  # 同步停止状态

# RPC 函数，用于同步动画状态
@rpc("authority", "call_remote", "reliable")
func sync_anim_state(state: int):
	p_anim_state = state
	update_animation()  # 收到同步后更新动画

# 本地更新动画播放
func update_animation():
	match p_anim_state:
		anim_state.RUN:
			if velocity.x < 0:
				sprite.flip_h = true
			else:
				sprite.flip_h = false
			sprite.play("run")
		anim_state.IDLE:
			sprite.play("idle")
		anim_state.ATTACK:
			sprite.play("atc2")


# 设置角色名称
func named(nam: String):
	$Label.text = nam

# 设置角色外观
func set_p_mod(toy: String):
	if toy == "p2":
		$p1.sprite_frames = load("res://tscn/players.tres")
	else:
		$p1.sprite_frames = load("res://tscn/player1.tres")

func dis_text(new_text:String):
	$Label2.text = new_text
	$Label2.visible = true
	$Timer.start()


func _on_timer_timeout():
	$Label2.visible = false
